package com.xingfei.blog.controller.base;

import com.alibaba.dubbo.common.json.JSON;
import com.alibaba.dubbo.common.json.ParseException;
import com.xingfei.blog.redisCluster.dao.RedisClusterDao;
import com.xingfei.blog.utils.CookieUtil;
import com.xingfei.blog.utils.RedisUtil;
import com.xingfei.blog.vo.UserVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * Created with IntelliJ IDEA.
 * 抽取前端公共数据
 * @author: chenxingfei
 * @time: 2017/3/12  9:40
 * To change this template use File | Settings | File Templates.
 */
public class BaseController {

    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private RedisClusterDao redisClusterDao;

    /**
     * 重定向路径
     * @param url
     * @return
     */
    protected String redirectTo(String url){
        StringBuffer rto = new StringBuffer("redirect:");
        rto.append(url);
        return rto.toString();
    }

    /**
     * 从cookie中获取token
     * @return
     */
    public String getTokenFromCookie(HttpServletRequest request){
        return CookieUtil.getCookieValue(request, "token");
    }

    /**
     * 根据cookie获取用户数据
     * @param request
     * @return
     */
    protected UserVO getUserVoByCookie(HttpServletRequest request){
        //获取用户当前登陆状态
        Cookie cookie = CookieUtil.getCookie(request, "token");
        UserVO userVO = null;
        if (cookie != null) {
            String token = cookie.getValue();
            if (org.apache.commons.lang3.StringUtils.isNotBlank(token)) {
                String s = redisClusterDao.get("user:" + token);
                try {
                    if(org.apache.commons.lang3.StringUtils.isNotBlank(s)){
                        userVO = JSON.parse(s, UserVO.class);
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        }
        return userVO;
    }
}
